package com.walter.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @author Walter
 * @date 2025/2/5 下午1:00
 **/
@Component
@Slf4j
public class TraceIdFilter implements GlobalFilter, Ordered {
    private static final String TRACE_ID_HEADER_NAME = "X-Trace-Id"; // 自定义 TraceId Header 名称
    private static final String TRACE_ID_MDC_KEY = "traceId";      // MDC 中 TraceId 的 key

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String traceId = generateTraceId(); // 生成 TraceId
        MDC.put(TRACE_ID_MDC_KEY, traceId);   // 放入 MDC
        ServerHttpRequest request = exchange.getRequest().mutate()
                .header(TRACE_ID_HEADER_NAME, traceId) // 添加 TraceId Header 到请求
                .build();
        ServerWebExchange modifiedExchange = exchange.mutate().request(request).build();

        return chain.filter(modifiedExchange)
                .doFinally(signalType -> {
                    // 请求结束后从 MDC 中移除 TraceId，避免线程污染
                    MDC.remove(TRACE_ID_MDC_KEY);
                });
    }

    @Override
    public int getOrder() {
        // 确保 Filter 优先级最高，尽早执行
        return Ordered.HIGHEST_PRECEDENCE;
    }

    private String generateTraceId() {
        // 使用 UUID 生成 TraceId
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
